//AUTHOR: Josh High
//COURSE: ISTM 415.502 
//FORM: PropertyController.cs 
//PURPOSE: This controller manages CRUD operations for properties, allowing users to add, edit, view, and delete 
// property records within the application.
//INITIALIZE: Requires proper setup of the Property model, the corresponding views (List, AddEdit, Delete), 
// and the JasperGreenContext database context with seeded data.
//INPUT: User inputs from property-related forms, such as property address, city, state, zip, and associated crew/customer IDs.
//PROCESS: Retrieves property data from the database, provides the correct view for each action (list, add, edit, delete),
// validates and saves form submissions, and manages database changes through Entity Framework Core.
//OUTPUT: Displays a list of properties and renders forms to modify or delete property information. Reflects all changes in the UI.
//TERMINATE: Database connections are managed through Entity Framework Core and are closed automatically after each request.
//HONOR CODE: “On my honor, as an Aggie, I have neither given
// nor received unauthorized aid on this academic
// work.”

using JasperGreenTeam11.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

namespace JasperGreenTeam11.Controllers
{
    public class PropertyController : Controller
    {
        private readonly JasperGreenContext context;

        // Constructor to inject the context
        public PropertyController(JasperGreenContext ctx) => context = ctx;

        // Redirect to the List action (home page for the Property section)
        public IActionResult Index() => RedirectToAction("List");

        // List all properties
        public IActionResult List()
        {
            var properties = context.Properties
                .Include(p => p.Customer)
                .Include(p => p.Crews)
                .OrderBy(p => p.PropertyId)
                .ToList();

            return View(properties);
        }

        // GET: Add Property
        [HttpGet]
        public IActionResult Add()
        {
            ViewBag.Action = "Add";

            // Create a list of EmployeeViewModel, and order by FullName
            var employees = context.Employees
    .Select(e => new Employee
    {
        EmployeeId = e.EmployeeId,
        FirstName = e.FirstName,
        LastName = e.LastName
    })
    .AsEnumerable()  // Switch to client-side evaluation
    .OrderBy(e => e.FullName)  // Order by computed FullName
    .ToList();

            // Convert the list of EmployeeViewModel to SelectList
            ViewBag.Employees = new SelectList(employees, "EmployeeId", "FullName");

            // Set customers in the ViewBag (no change here)
            ViewBag.Customers = new SelectList(context.Customers.OrderBy(c => c.FirstName), "CustomerId", "FullName");

            return View("AddEdit", new Property());
        }


        // GET: Edit Property
        [HttpGet]
        public IActionResult Edit(int id)
        {
            ViewBag.Action = "Edit";

            var property = context.Properties.Find(id);

            // Create a list of EmployeeViewModel, and order by FullName
            var employees = context.Employees
                .Select(e => new Employee
                {
                    EmployeeId = e.EmployeeId,
                    FirstName = e.FirstName,
                    LastName = e.LastName
                })
                       .AsEnumerable() // Switch to in-memory evaluation  

                .OrderBy(e => e.FullName)  // Order by computed FullName
                .ToList();

            // Pass selected employees to the ViewBag for Crew Foreman, Member1, and Member2
            ViewBag.Employees = new SelectList(employees, "EmployeeId", "FullName", property.CrewForemanId);
            ViewBag.Employees = new SelectList(employees, "EmployeeId", "FullName", property.CrewMember1Id);
            ViewBag.Employees = new SelectList(employees, "EmployeeId", "FullName", property.CrewMember2Id);

            // Pass customers to the ViewBag (no change here)
            ViewBag.Customers = new SelectList(context.Customers.OrderBy(c => c.FirstName), "CustomerId", "FullName", property.CustomerId);

            return View("AddEdit", property);
        }


        // POST: Save Property (Add or Edit)
        [HttpPost]
        public IActionResult Save(Property property)
        {
            if (ModelState.IsValid)
            {
                if (property.PropertyId == 0)
                {
                    context.Properties.Add(property);
                }
                else
                {
                    context.Properties.Update(property);
                }

                context.SaveChanges();
                return RedirectToAction("List");
            }
            else
            {
                ViewBag.Action = property.PropertyId == 0 ? "Add" : "Edit";
                ViewBag.Customers = new SelectList(context.Customers.OrderBy(c => c.FirstName), "CustomerId", "FullName", property.CustomerId);
                return View("AddEdit", property);
            }
        }

        // GET: Delete Property
        [HttpGet]
        public IActionResult Delete(int id)
        {
            var property = context.Properties.Find(id);
            if (property == null)
            {
                return NotFound(); // Return NotFound if property doesn't exist
            }
            return View(property); // Return the Delete confirmation view
        }

        // POST: Confirm Delete Property
        [HttpPost]
        public IActionResult Delete(Property property)
        {
            // Remove the property from the database
            context.Properties.Remove(property);
            context.SaveChanges();
            return RedirectToAction("List"); // Redirect back to the property list after deletion
        }
    }
}
